<template>
  <div class="page-container">
    <ShipVerticalTabNav :ship-id="shipId" :ship-name="shipName" />
    
    <div class="ship-radar-container">
      <!-- 标题栏与返回按钮 -->
      <div class="page-header">
        <div class="left-area">
          <!-- <el-button @click="goBack" class="back-button">
            <el-icon><ArrowLeft /></el-icon>
            返回船舶列表
          </el-button> -->
          <h2 class="page-title"> 雷达扫描数据</h2>
        </div>
        <div class="right-area">
          <el-button type="primary" @click="handleAdd" class="custom-button">
            <el-icon><Plus /></el-icon>新增雷达数据
          </el-button>
        </div>
      </div>

      <!-- 表格区域 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
        height="calc(100vh - 250px)"
        :header-cell-style="{ background: 'var(--el-bg-color-page)' }"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="序号" type="index" width="80" align="center" />
        <el-table-column label="船舶" min-width="150" align="center">
          <template #default="{ row }">
            {{ getShipName(row.shipCode || row.shipId) }}
          </template>
        </el-table-column>
        <el-table-column label="记录时间" prop="recordTime" width="180" align="center">
          <template #default="scope">
            {{ formatDateTime(scope.row.recordTime) }}
          </template>
        </el-table-column>
        <el-table-column label="经度" prop="lon" width="150" align="center">
          <template #default="scope">
            {{ formatCoordinate(scope.row.lon) }}
          </template>
        </el-table-column>
        <el-table-column label="纬度" prop="lat" width="150" align="center">
          <template #default="scope">
            {{ formatCoordinate(scope.row.lat) }}
          </template>
        </el-table-column>
        <el-table-column label="航向(度)" prop="cog" width="120" align="center">
          <template #default="scope">
            {{ Number(scope.row.cog).toFixed(2) }}°
          </template>
        </el-table-column>
        <el-table-column label="航速(节)" prop="sog" width="120" align="center">
          <template #default="scope">
            {{ Number(scope.row.sog).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="访问角(度)" prop="azimuth" width="120" align="center">
          <template #default="scope">
            {{ Number(scope.row.azimuth).toFixed(2) }}°
          </template>
        </el-table-column>
        <el-table-column label="信号强度(dB)" prop="signalStrength" width="140" align="center">
          <template #default="scope">
            {{ Number(scope.row.signalStrength).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right" align="center">
          <template #default="scope">
            <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 编辑/新增弹窗 -->
      <el-dialog
        v-model="dialogVisible"
        :title="dialogType === 'add' ? '新增雷达扫描数据' : '编辑雷达扫描数据'"
        width="50%"
        destroy-on-close
      >
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="120px"
          class="dialog-form"
        >
          <el-form-item label="选择船舶" prop="shipCode">
            <el-select v-model="form.shipCode" placeholder="请选择船舶" style="width: 100%" @change="(val) => shipCodeChanged(val)">
              <el-option
                v-for="item in shipOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="记录时间" prop="recordTime">
            <el-date-picker
              v-model="form.recordTime"
              type="datetime"
              placeholder="选择记录时间"
              style="width: 100%"
            />
          </el-form-item>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="经度" prop="lon">
                <el-input-number
                  v-model="form.lon"
                  :precision="8"
                  :step="0.00000001"
                  :controls="false"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="纬度" prop="lat">
                <el-input-number
                  v-model="form.lat"
                  :precision="8"
                  :step="0.00000001"
                  :controls="false"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="航向(度)" prop="cog">
                <el-input-number
                  v-model="form.cog"
                  :precision="2"
                  :min="0"
                  :max="360"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="航速(节)" prop="sog">
                <el-input-number
                  v-model="form.sog"
                  :precision="2"
                  :min="0"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="访问角(度)" prop="azimuth">
                <el-input-number
                  v-model="form.azimuth"
                  :precision="2"
                  :min="0"
                  :max="360"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="信号强度(dB)" prop="signalStrength">
                <el-input-number
                  v-model="form.signalStrength"
                  :precision="2"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <template #footer>
          <span>
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="submitForm">确 定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { ArrowLeft, Plus } from "@element-plus/icons-vue";
import dayjs from "dayjs";
import { useRouter, useRoute } from "vue-router";
import { 
  getShipRadarScanDataList, 
  getShipRadarScanDataById, 
  addShipRadarScanData, 
  updateShipRadarScanData, 
  deleteShipRadarScanData,
  getShipInfoList,
  getShipInfoById
} from "@/api/bridge/bisc/ship";
import ShipVerticalTabNav from '@/views/Bridge/basic-data/components/ShipVerticalTabNav.vue';

// 路由相关
const router = useRouter();
const route = useRoute();
const shipId = ref<string | null>(null);
const shipName = ref<string | null>(null);

// 表格数据
const tableData = ref<any[]>([]);
const loading = ref(false);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);

// 船舶选项列表
const shipOptions = ref<Array<{value: string, label: string}>>([]);

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
});

// 船舶查询参数
const shipQueryParams = reactive({
  pageNum: 1,
  pageSize: 1000000, // 获取大量数据以确保能获取所有船舶
});

// 根据shipId获取船舶名称
const getShipNameById = computed(() => {
  if (!shipId.value || shipOptions.value.length === 0) return '未知船舶';
  
  const ship = shipOptions.value.find(item => item.value === shipId.value);
  return ship ? ship.label : '未知船舶';
});

// 获取所有船舶数据
const getAllShips = async () => {
  try {
    const res = await getShipInfoList(shipQueryParams);
    shipOptions.value = res.rows.map((item: any) => ({
      value: item.id,
      label: item.nameCn || item.nameEn || '未命名船舶',
    }));
    
    // 如果路由中传递了船舶名称，优先使用；否则根据shipId查找
    if (route.query.shipName) {
      shipName.value = route.query.shipName as string;
    } else if (shipId.value) {
      shipName.value = getShipNameById.value;
    }
  } catch (error) {
    console.error("获取船舶列表失败:", error);
    ElMessage.error("获取船舶列表失败");
  }
};

// 弹窗控制
const dialogVisible = ref(false);
const dialogType = ref<"add" | "edit">("add");



// 表单校验规则
const rules = {
  shipCode: [{ required: true, message: "请选择船舶", trigger: "change" }],
  recordTime: [{ required: true, message: "请选择记录时间", trigger: "change" }],
  lat: [{ required: true, message: "请输入纬度", trigger: "blur" }],
  lon: [{ required: true, message: "请输入经度", trigger: "blur" }],
  cog: [{ required: true, message: "请输入航向", trigger: "blur" }],
  sog: [{ required: true, message: "请输入航速", trigger: "blur" }],
  azimuth: [{ required: true, message: "请输入访问角", trigger: "blur" }],
  signalStrength: [{ required: true, message: "请输入信号强度", trigger: "blur" }],
};

// 格式化日期时间
const formatDateTime = (date: string | number | Date) => {
  if (!date) return "-";
  
  // 如果是时间戳字符串，先转换为数字
  if (typeof date === 'string' && /^\d+$/.test(date)) {
    return dayjs(parseInt(date)).format('YYYY-MM-DD HH:mm:ss');
  }
  
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss');
};

// 格式化坐标，保留8位小数
const formatCoordinate = (value: number | string) => {
  if (value === undefined || value === null) return "-";
  
  return Number(value).toFixed(8);
};

// 获取列表数据
const getList = async () => {
  loading.value = true;
  try {
    queryParams.pageNum = currentPage.value;
    queryParams.pageSize = pageSize.value;
    
    // 只有当shipId有值时才将其添加到查询参数中
    const params: any = { ...queryParams };
    if (shipId.value) {
      params.shipId = shipId.value;
    }

    const res = await getShipRadarScanDataList(params);
    tableData.value = res.rows || [];
    total.value = res.total || 0;
  } catch (error) {
    console.error("获取雷达扫描数据列表失败:", error);
    ElMessage.error("获取雷达扫描数据列表失败");
  } finally {
    loading.value = false;
  }
};

// 返回船舶列表
const goBack = () => {
  router.push('/basic-data/boat');
};

// 处理分页
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  getList();
};

const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  getList();
};

// 新增
const handleAdd = () => {
  dialogType.value = "add";
  form.value = {
    id: "",
    shipCode: shipId.value || "", // 如果路由参数有shipId，则默认选中
    recordTime: new Date(),
    lat: 0,
    lon: 0,
    cog: 0,
    sog: 0,
    azimuth: 0,
    signalStrength: 0,
  };
  
  // 如果有shipId，自动设置相关信息
  if (shipId.value) {
    getShipInfoById(shipId.value).then(res => {
      if (res.data) {
        // 这里可以设置其他与船舶相关的字段，如果需要的话
        // 雷达数据可能不需要设置太多船舶信息字段
      }
    }).catch(error => {
      console.error("获取船舶详情失败:", error);
    });
  }
  
  dialogVisible.value = true;
};

// 编辑
const handleEdit = async (row: any) => {
  try {
    loading.value = true;
    const res = await getShipRadarScanDataById(row.id);
    dialogType.value = "edit";
    
    // 处理时间字段，确保在表单中正确显示
    const data = { ...res.data };
    
    // 如果recordTime是时间戳字符串，将其转换为日期对象
    if (data.recordTime && typeof data.recordTime === 'string' && /^\d+$/.test(data.recordTime)) {
      data.recordTime = new Date(parseInt(data.recordTime));
    }
    
    // 确保映射shipId到shipCode
    if (data.shipId && !data.shipCode) {
      data.shipCode = data.shipId;
    }
    
    form.value = data;
    dialogVisible.value = true;
  } catch (error) {
    console.error("获取雷达扫描数据详情失败:", error);
    ElMessage.error("获取雷达扫描数据详情失败");
  } finally {
    loading.value = false;
  }
};

// 删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm("确认删除该雷达扫描数据吗？", "警告", {
    type: "warning",
  })
    .then(async () => {
      try {
        await deleteShipRadarScanData(row.id);
        ElMessage.success("删除成功");
        getList();
      } catch (error) {
        console.error("删除雷达扫描数据失败:", error);
        ElMessage.error("删除雷达扫描数据失败");
      }
    })
    .catch(() => {});
};

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;
  
  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        // 处理表单数据
        if(shipId.value && typeof form.value.shipCode === 'string'){
          form.value.shipCode = shipId.value;
        }
        let submitData = { ...form.value ,
        };
        
        // 使用dayjs格式化日期时间，不再使用时间戳
        if (submitData.recordTime instanceof Date) {
          submitData.recordTime = dayjs(submitData.recordTime).format('YYYY-MM-DD HH:mm:ss');
        } else if (submitData.recordTime && typeof submitData.recordTime === 'string' && !(/^\d+$/.test(submitData.recordTime))) {
          // 如果是日期字符串但不是时间戳格式，也进行格式化
          submitData.recordTime = dayjs(submitData.recordTime).format('YYYY-MM-DD HH:mm:ss');
        }
        
        if (dialogType.value === "add") {
          await addShipRadarScanData(submitData);
          ElMessage.success("新增成功");
        } else {
          await updateShipRadarScanData(submitData);
          ElMessage.success("修改成功");
        }
        dialogVisible.value = false;
        getList();
      } catch (error) {
        console.error("操作失败:", error);
        ElMessage.error("操作失败");
      }
    }
  });
};

// 根据船舶ID获取船舶名称
const getShipName = (id: string) => {
  console.log(id);
  if (!id || shipOptions.value.length === 0) return '未知船舶';
  
  const ship = shipOptions.value.find(item => item.value === id);
  return ship ? ship.label : '未知船舶';
};

// 表单数据
const formRef = ref();
const form = ref({
  id: "",
  shipCode: "", // 对应船舶ID，向后端传递为shipCode
  recordTime: null as null | Date | string, // 记录时间，可以是日期对象或字符串
  lat: 0, // 纬度
  lon: 0, // 经度
  cog: 0, // 航向
  sog: 0, // 航速
  azimuth: 0, // 访问角
  signalStrength: 0, // 信号强度
});

// 船舶选择变化处理函数
const handleShipChange = (shipCode: string) => {
  if (!shipCode || shipOptions.value.length === 0) return;
  
  // 这里可以添加船舶选择后的处理逻辑
  // 雷达数据表单可能不需要自动填充其他船舶信息字段
};

// 船舶选择变化处理函数
const shipCodeChanged = (shipCode: string) => {
  if (!shipCode || shipOptions.value.length === 0) return;
  
  // 这里可以添加船舶选择后的处理逻辑
  // 雷达数据表单可能不需要自动填充其他船舶信息字段
};

onMounted(() => {
  // 从路由参数获取船舶ID
  shipId.value = route.query.shipId as string || null;
  form.value.shipCode = getShipName(shipId.value || "");
  // 先获取所有船舶信息
  getAllShips().then(() => {
    // 获取雷达扫描数据
    getList();
  });
});
</script>

<style scoped lang="scss">
.page-container {
  display: flex;
  height: 100%;
  background: var(--el-bg-color-page);
  border-radius: 4px;
  box-shadow: var(--el-box-shadow-light);
  overflow: hidden;
}

.ship-radar-container {
  flex: 1;
  padding: 20px;
  overflow: auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  background: var(--el-bg-color-overlay);
  padding: 16px;
  border-radius: 4px;

  .left-area {
    display: flex;
    align-items: center;
    gap: 12px;

    .back-button {
      display: flex;
      align-items: center;
      gap: 4px;
      transition: all 0.3s;

      &:hover {
        transform: translateX(-2px);
      }
    }

    .page-title {
      margin: 0;
      font-size: 18px;
      color: var(--el-text-color-primary);
      position: relative;
      padding-left: 15px;

      &::before {
        content: "";
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 4px;
        height: 18px;
        background: var(--el-color-primary);
        border-radius: 2px;
      }
    }
  }

  .right-area {
    .custom-button {
      position: relative;
      overflow: hidden;
      transition: all 0.3s ease;

      &::before {
        content: "";
        position: absolute;
        top: 50%;
        left: 50%;
        width: 0;
        height: 0;
        background: rgba(255, 255, 255, 0.2);
        border-radius: 50%;
        transform: translate(-50%, -50%);
        transition: width 0.6s ease, height 0.6s ease;
      }

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);

        &::before {
          width: 300px;
          height: 300px;
        }
      }

      &:active {
        transform: translateY(1px);
      }
    }
  }
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-form {
  :deep(.el-input-number) {
    width: 100%;
  }
}
</style> 